/**
 *
 * ......................我佛慈悲.......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG....................
 *         CSDN博客:http://blog.csdn.net/song5347
 *       github地址:https://github.com/lingsuiderongyan
 *             邮箱:lingsuiderongyan@163.com
 */
//发微博配图
import UIKit

//MARK: - 重用标记
private let LSComposePictureViewCellIdentifier = "LSComposePictureViewCellIdentifier"

class LSComposePictuerView: UICollectionView {
    
    //点击加号按钮执行的闭包
    var didSeletedAddimageViewClosure: (()->())?
    
    //图片数据源
    lazy var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {

        //默认状态当前配图隐藏
        hidden = true
        
        //注册cell
        registerClass(LSComposePictureViewCell.self, forCellWithReuseIdentifier: LSComposePictureViewCellIdentifier)
        
        //设置数据源代理
        dataSource = self
        //设置代理
        delegate = self
    }
    
    //MARK: - 添加图片方法
    func addImage(image: UIImage) {
        
        if images.count > 8 {
            return
        }
        
        //显示配图
        hidden = false
        
        //添加图片
        images.append(image)
        
        //重新加载数据
        self.reloadData()
    }
    
    override func layoutSubviews() {
         super.layoutSubviews()
        //设置每项间距
        let itemMargin: CGFloat = 5
        //计算每项的大小
        let itemWidth = (width - 2 * itemMargin) / 3
        //获取布局方式
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //设置水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        //设置垂直间距
        flowLayout.minimumLineSpacing = itemMargin
    }
}

//MARK: - UICollectionViewDataSource实现数据原代理方法
extension LSComposePictuerView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //如果是0或9张,需需要多现实一个单元格
        if images.count == 0 || images.count == 9 {
            return images.count
        } else {
            return images.count + 1    //否则要多显示一个加号cell
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LSComposePictureViewCellIdentifier, forIndexPath: indexPath) as! LSComposePictureViewCell
        
        //indexPath.item索引等于数组的个数表示最后一个cell
        if indexPath.item == images.count {
            cell.image = nil
            
        } else {
            //绑定图片
            cell.image = images[indexPath.item]
            
            //设置删除图片闭包
            cell.deleteButtonClosure = { [weak self] in
                //通过数据源删除指定图片
                self?.images.removeAtIndex(indexPath.item)
                
                //判断数据源是否为0
                if self?.images.count == 0 {
                    //隐藏当前配图
                    self?.hidden = true
                }
                self?.reloadData()
            }
        }
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //如果索引等于数组的个数,表示最后一个cell
        if indexPath.item == images.count {
            //取消选中
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)
            //执行闭包
            didSeletedAddimageViewClosure?()
        }
    }
}

//MARK: - 自定义发微博图片cell
class LSComposePictureViewCell: UICollectionViewCell {
    
    //MARK: - 点击删除按钮执行的闭包
    var deleteButtonClosure: (()->())?
    
    var image: UIImage? {
        didSet {
            if image == nil{
                //添加加号按钮图片
                imageView.image = UIImage(named: "compose_pic_add")
                //添加高亮图片
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                //如果是设置加号图片就隐藏删除按钮
                deleteButton.hidden = true
            } else {
                //设置绑定图片
                imageView.image = image
                //显示删除按钮
                deleteButton.hidden = false
                //删除高亮图片
                imageView.highlightedImage = nil
            }
        }
    }
    
    //MARK: - 懒加载控件
    private lazy var imageView: UIImageView = UIImageView()
    
    //MARK: - 删除按钮
    private lazy var deleteButton: UIButton = {
        
        let button = UIButton()
        
        button.addTarget(self, action: "deleteButtonAction", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 添加控件设置约束
    private func setupUI() {
        //backgroundColor = RandomColor()
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    //MARK: - 监听点击事件
    @objc private func deleteButtonAction() {
        print("~~~~~~~~~~~~")
        //执行删除的闭包
        deleteButtonClosure?()
    }
}














